package com.hzw.net.utils.recyclerview;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * Copyright (c) 2019, 四川绿源集科技有限公司 All rights reserved.
 * author：HuaZhongWei
 * date：2019/4/16
 * description：
 **/
public class CommonGridLayoutItemDecoration1 extends RecyclerView.ItemDecoration {

    private int spanCount; //列数

    private int top; //顶部
    private int bottom; //底部
    private int start; //顶部
    private int end; //底部


    private int spacingV; //垂直间隔
    private int spacingH; //横向间隔


    public CommonGridLayoutItemDecoration1(int spanCount, int top, int bottom, int start, int end, int spacingV, int spacingH) {
        this.spanCount = spanCount;
        this.top = top;
        this.bottom = bottom;
        this.start = start;
        this.end = end;
        this.spacingV = spacingV;
        this.spacingH = spacingH;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        //这里是关键，需要根据你有几列来判断
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column
        int itemCount = parent.getAdapter().getItemCount();

        int lastRowCount = itemCount % spanCount == 0 ? spanCount : itemCount % spanCount;

        if (column == 0) {  //最左
            outRect.left = start;
            outRect.right = (column + 1) * spacingH / spanCount;
        } else if (column == spanCount - 1) { //最右
            outRect.right = end;
            outRect.left = spacingH - column * spacingH / spanCount;
        } else {
//            outRect.left = column * spacingH / spanCount; // column * ((1f / spanCount) * spacing)
//            outRect.right = spacingH - (column + 1) * spacingH; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            outRect.left = spacingH - column * spacingH / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacingH / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
        }

        if (position < spanCount) { // 最上
            outRect.top = top;
            outRect.bottom = spacingV;
        } else if (position >= itemCount - lastRowCount) { //最下
            outRect.bottom = bottom;
        } else {
            outRect.bottom = spacingV;
        }
    }
}
